package bcxd.firstline.supplier.machining;

import java.sql.Connection;
import java.util.Map;

import jt.classic.system.context.ISystemContext;
import jt.classic.system.database.SystemDataSource;
import jt.classic.system.user.IUser;

import org.limp.basework.MachiningException;
import org.limp.basework.SimpleBean;
import org.limp.basework.SimpleBean4Table;
import org.limp.basework.SimpleBeanMachining;
import org.limp.basework.Table;
import org.limp.basework.impl.CommonBean4HSQ;
import org.limp.basework.impl.SimpleBean4TableImpl;
import org.limp.basework.tools.BaseworkUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import bcxd.firstline.user.manager.AppUserManager;

/**
 * 供应商入驻信息资料更新
 * 
 * @author mido
 * 
 */
public class CompanyApplyMachining implements SimpleBeanMachining {

	private static final Logger LOG = LoggerFactory
			.getLogger(CompanyApplyMachining.class);

	@SuppressWarnings( { "unchecked", "rawtypes" })
	public SimpleBean machining(SimpleBean bean, Table table,
			CommonBean4HSQ request, Connection conn, int type)
			throws MachiningException {

		LOG.debug("type={}", type);

		if (type == 3) {

			if (ISystemContext.invalidSesstion(request.getRequest())) {
				throw new MachiningException("invalid session.");
			}
			// 更新会话用户对象信息
			IUser user = ISystemContext.getSessionUser(request.getRequest());

			SimpleBean4Table userBean = new SimpleBean4TableImpl("bcxduser");
			userBean.getResource().put("uid", user.id());
			userBean.getResource().put("uname",
					request.getResource().get("fcname"));
			userBean.getResource().put("ustatus", "1");

			//更新核心企业的供应商名录信息中的相关内容信息 是否有必要?
			//coding...

			BaseworkUtil util = new BaseworkUtil();
			try {
				util.manualUpdate1(userBean, conn);
			} catch (Exception ex) {
				throw new MachiningException("update application-user error.",
						ex);
			}

		} else if (type == 4000) {
			// 入驻资料更新成功,重置会话
			IUser user = ISystemContext.getSessionUser(request.getRequest());
			// 首次入驻更新资料信息,更新后重置会话
			if (user.iflag() == 0) {
				Connection newConn = null;
				try {
					SystemDataSource ds = SystemDataSource.getInstance();
					newConn = ds.getConnection();

					AppUserManager manager = new AppUserManager(newConn);

					IUser appUser = manager.getBcxdUserById(user.id());

					ISystemContext.resetSessionUser(request.getRequest(),
							appUser);
				} catch (Exception ex) {
					SystemDataSource.rollbackConnection(newConn);
					throw new MachiningException("get application-user error.",
							ex);
				} finally {
					SystemDataSource.closeConnection(newConn);
				}
			}
		}
		return null;
	}

}
